﻿using Datav.Design.IService;
using Zdap.Common.IdGenerate;

namespace Datav.Design.Service
{
    /// <summary>
    /// 图像验证码服务
    /// </summary>
    public class CaptchaService : ICaptchaService
    {
        private const string RedisKey = "SLRH_Captcha_:{0}";

        /// <summary>
        /// 获取图像验证码数据
        /// </summary>
        /// <param name="type">验证码类型（0-普通验证码 1-算数计算验证码）</param>
        /// <param name="width">验证码图片宽度</param>
        /// <param name="height">验证码图片高度</param>
        /// <param name="length">验证码字符个数</param>
        /// <param name="pid">验证码唯一ID（由服务端雪花算法生成并返回，验证的时候传回服务端）</param>
        public CaptchaResult GetVerifyCode(CaptchaType type = CaptchaType.Normal, int width = 120, int height = 30, int length = 4, long pid = 0)
        {
            if (pid > 0)
            {
                var oldKey = GetRedisKey(pid);
                RedisHelper.Del(oldKey);
            }
            var result = CaptchaUtility.GetVerifyCode(width, height, length, captchaType: type);
            result.Id = IdWorker.NextId();
            RedisHelper.Set(GetRedisKey(result.Id), result.CaptchaValue, 3 * 60);
            return result;
        }

        /// <summary>
        /// 验证输入的验证码
        /// </summary>
        /// <param name="id">验证码唯一Id</param>
        /// <param name="inputCode">输入的验证码</param>
        public (bool Success, string Msg) Validate(long id, string inputCode)
        {
            if (string.IsNullOrWhiteSpace(inputCode))
            {
                return (false, "验证码为空！");
            }
            var redisKey = GetRedisKey(id);
            var redisCode = RedisHelper.Get(redisKey);
            if (redisCode is null)
            {
                return (false, "验证码已过期！");
            }
            RedisHelper.Del(redisKey);

            if (!string.Equals(inputCode.Trim(), redisCode, StringComparison.OrdinalIgnoreCase))
            {
                return (false, "验证码输入错误！");
            }
            return (true, "验证码输入正确！");
        }

        /// <summary>
        /// 获取存储的Redis键
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private static string GetRedisKey(long id)
        {
            return string.Format(RedisKey, id);
        }
    }
}